import { useState, useEffect } from 'react';
import moment from 'moment';

export const format = ['00', '00', '00', '00', '000'];
export const type_enum = {
  one: 1, //正常时分秒
  two: 2, // 小于48小时 小时位最大可展示48
};
/**
 *
 * @param endTime 倒计时结束时间
 * @param type 倒计时小时位展示类型
 * @param cb 倒计时结束回调
 * @returns {*}
 */
const useCountDown = (_endTime, type = type_enum.one, cb) => {
  const [countDown, setCountDown] = useState(format);
  useEffect(() => {
    // 将请求依赖合并成请求参数
    const timer = setInterval(() => {
      const endTime = moment(_endTime);
      let _ms = endTime.diff(moment());
      if (_ms > 0) {
        let _dd = endTime.diff(moment(), 'day');
        let _hh = endTime.diff(moment(), 'hour');
        let _mm = endTime.diff(moment(), 'minute');
        let _ss = endTime.diff(moment(), 'second');

        let hh = _hh - _dd * 24;
        let mm = _mm - _hh * 60;
        let ss = _ss - _mm * 60;
        let ms = _ms - _ss * 1000;

        // 显示48小时
        if (type === type_enum.two && _dd < 2) {
          hh = _hh;
        }

        // 格式化
        let DD = (format[0] + _dd).slice(-format[0].length);
        let HH = (format[1] + hh).slice(-format[1].length);
        let MM = (format[2] + mm).slice(-format[2].length);
        let SS = (format[3] + ss).slice(-format[3].length);
        let MS = (format[4] + ms).slice(-format[4].length);
        setCountDown([DD, HH, MM, SS, MS]);
      } else {
        timer && clearInterval(timer);
        setCountDown(format);
        cb && cb();
      }
    }, 1000);
    return () => {
      timer && clearInterval(timer);
    };
  }, [_endTime]);
  return countDown;
};

export default useCountDown;
